﻿using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.Common;
using KWT.DRG_DIP.DO.System;
using KWT.DRG_DIP.DTO.qcRules;
using KWT.DRG_DIP.PO.qcRules;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace KWT.DRG_DIP.API.Controllers.qcRules
{
    /// <summary>
    /// 值域
    /// </summary>
    [ApiExplorerSettings(GroupName = "qc")]
    [AllowAnonymous]
    public class ValueRangeController : QCControllerBase
    {
        #region 添加或编辑
        /// <summary>
        /// 添加或编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<OutputResult> AddOrUpdate(InValueRange dto)
        {

            var valueRange = _mapper.Map<qc_Rules_ValueRange>(dto);
            var valueRangeInfos = _mapper.Map<List<qc_Rules_ValueRangeInfo>>(dto.LstValueRangeInfo);

            if (!ef.Set<qc_Rules_ValueRange>().Any(x => x.VRID == dto.VRID))
            {
                if (ef.Set<qc_Rules_ValueRange>().Any(x => x.name == dto.name))
                {
                    return Fail("值域名称重复！");
                }

                valueRange.VRID = "VR" + snow_id.CreateId().ToString();
                dto.VRID = valueRange.VRID;
                ef.Add(valueRange);
            }
            else
            {
                if (ef.Set<qc_Rules_ValueRange>().Any(x => x.name == dto.name&&x.VRID!= dto.VRID))
                {
                    return Fail("值域名称重复！");
                }

                var para = ef.Find<qc_Rules_ValueRange>(dto.VRID);
                if (para == null)
                {
                    return Fail("该项不存在！");
                }
                para.name = dto.name;
                para.remark = dto.remark;
                ef.Update(para);
            }
    
            await ef.Set<qc_Rules_ValueRangeInfo>().Where(x => x.VRID == dto.VRID).ExecuteDeleteAsync();
            valueRangeInfos.ForEach(x => { x.VRID = dto.VRID; x.ID = "VR" + snow_id.CreateId().ToString(); });
            ef.AddRange(valueRangeInfos);

            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }
        #endregion

        #region 批量删除
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="vrIDs">值域IDs</param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult Del([FromQuery] string[] vrIDs)
        {
            using (var transaction = ef.Database.BeginTransaction())
            {
                try
                {
                    var flag = ef.Set<qc_Rules_ValueRange>().Where(x => vrIDs.Contains(x.VRID)).ExecuteDelete() > 0;
                    ef.Set<qc_Rules_ValueRangeInfo>().Where(x => vrIDs.Contains(x.VRID)).ExecuteDelete();
                    transaction.Commit(); // 手动提交
                    return Output(flag, "操作成功", "操作失败");
                }
                catch(Exception ex)
                {
                    transaction.Rollback(); // 手动回滚

                    return Fail(ex.Message);
                }
            }
            
        }
        #endregion

        #region 根据值域ID查看明细
        /// <summary>
        /// 根据值域ID查看明细
        /// </summary>
        /// <param name="vrID">值域ID</param>
        /// <returns></returns>
        [ProducesResponseType(typeof(Output<qc_Rules_ValueRangeInfo>), 200)]
        [HttpGet]
        public OutputResult GetInfoByID([FromQuery] string vrID)
        {
            var infos = ef.Set<qc_Rules_ValueRangeInfo>().Where(x => x.VRID == vrID).ToList();
            return Output(true, "操作成功", "操作失败", infos);

        }
        #endregion

        #region  根据名称查询值域(分页)
        /// <summary>
        /// 根据名称查询值域(分页)
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [ProducesResponseType(typeof(Output<InValueRangePage>), 200)]
        [HttpPost]
        public OutputResult PageList(InValueRangePage dto)
        {
            
            var q = ef.Set<qc_Rules_ValueRange>().AsQueryable();
            if (!string.IsNullOrEmpty(dto.name))
            {
                q = q.Where(x => EF.Functions.Like(x.name, $"%{dto.name}%"));
            }
            int total = q.Count();
            var list = q.ToPageList(dto.PageNo, dto.PageSize);
            return Output(true, "", "", new PageList<qc_Rules_ValueRange>() { List = list, Total = total });
        }
        #endregion
    }
}
